#include "config_manager.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <errno.h>

// Simple memory management wrappers for config manager
static inline void* config_alloc(size_t size) {
    return calloc(1, size);
}

static inline void config_free(void* ptr) {
    if (ptr) free(ptr);
}

// 创建配置管理器
config_manager_t* config_manager_create(const char *config_file) {
    config_manager_t *manager = config_alloc(sizeof(config_manager_t));
    if (!manager) {
        return NULL;
    }
    
    memset(manager, 0, sizeof(config_manager_t));
    
    // 设置配置文件路径
    if (config_file) {
        strncpy(manager->config_file, config_file, sizeof(manager->config_file) - 1);
    } else {
        strcpy(manager->config_file, "gudb.conf");
    }
    
    strcpy(manager->default_config_file, "gudb_default.conf");
    
    // 初始化读写锁
    if (pthread_rwlock_init(&manager->config_lock, NULL) != 0) {
        config_free(manager);
        return NULL;
    }
    
    manager->auto_save = true;
    manager->last_saved = 0;
    
    // 初始化默认配置参数
    config_init_default_params(manager);
    
    return manager;
}

// 销毁配置管理器
void config_manager_destroy(config_manager_t *manager) {
    if (!manager) return;
    
    // 自动保存配置
    if (manager->auto_save) {
        config_save_to_file(manager, manager->config_file);
    }
    
    // 销毁所有配置分组和参数
    config_group_t *group = manager->groups;
    while (group) {
        config_group_t *next_group = group->next;
        
        // 销毁分组中的所有参数
        config_param_t *param = group->params;
        while (param) {
            config_param_t *next_param = param->next;
            
            // 释放字符串类型的值
            if (param->type == CONFIG_TYPE_STRING && param->value.string_val) {
                config_free(param->value.string_val);
            }
            if (param->type == CONFIG_TYPE_STRING && param->default_value.string_val) {
                config_free(param->default_value.string_val);
            }
            
            config_free(param);
            param = next_param;
        }
        
        config_free(group);
        group = next_group;
    }
    
    // 销毁读写锁
    pthread_rwlock_destroy(&manager->config_lock);
    
    config_free(manager);
}

// 添加配置分组
int config_add_group(config_manager_t *manager, const char *group_name, 
                     const char *description) {
    if (!manager || !group_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    // 检查分组是否已存在
    if (config_get_group(manager, group_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1; // 分组已存在
    }
    
    // 创建新分组
    config_group_t *group = config_alloc(sizeof(config_group_t));
    if (!group) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(group, 0, sizeof(config_group_t));
    strncpy(group->name, group_name, sizeof(group->name) - 1);
    if (description) {
        strncpy(group->description, description, sizeof(group->description) - 1);
    }
    
    // 添加到链表头部
    group->next = manager->groups;
    manager->groups = group;
    manager->group_count++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 获取配置分组
config_group_t* config_get_group(config_manager_t *manager, const char *group_name) {
    if (!manager || !group_name) {
        return NULL;
    }
    
    config_group_t *group = manager->groups;
    while (group) {
        if (strcmp(group->name, group_name) == 0) {
            return group;
        }
        group = group->next;
    }
    
    return NULL;
}

// 定义整数配置参数
int config_define_int(config_manager_t *manager, const char *group_name, 
                     const char *param_name, const char *description,
                     int64_t default_value, int64_t min_value, int64_t max_value,
                     bool readonly, bool requires_restart) {
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    // 获取或创建分组
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    // 检查参数是否已存在
    if (config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1; // 参数已存在
    }
    
    // 创建新参数
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_INT;
    param->value.int_val = default_value;
    param->default_value.int_val = default_value;
    param->min_value.int_val = min_value;
    param->max_value.int_val = max_value;
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    // 添加到分组的参数链表
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 定义无符号整数配置参数
int config_define_uint(config_manager_t *manager, const char *group_name,
                      const char *param_name, const char *description,
                      uint64_t default_value, uint64_t min_value, uint64_t max_value,
                      bool readonly, bool requires_restart) {
    // 类似于config_define_int的实现，但使用CONFIG_TYPE_UINT和uint_val
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group || config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_UINT;
    param->value.uint_val = default_value;
    param->default_value.uint_val = default_value;
    param->min_value.uint_val = min_value;
    param->max_value.uint_val = max_value;
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 定义布尔配置参数
int config_define_bool(config_manager_t *manager, const char *group_name,
                      const char *param_name, const char *description,
                      bool default_value, bool readonly, bool requires_restart) {
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group || config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_BOOL;
    param->value.bool_val = default_value;
    param->default_value.bool_val = default_value;
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 设置整数配置参数
int config_set_int(config_manager_t *manager, const char *param_name, int64_t value) {
    if (!manager || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_INT || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    // 验证范围
    if (value < param->min_value.int_val || value > param->max_value.int_val) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    // 保存旧值用于回调
    config_value_t old_value = param->value;
    
    // 设置新值
    param->value.int_val = value;
    param->is_set = true;
    param->last_modified = time(NULL);
    
    // 调用变更回调
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 获取整数配置参数
int64_t config_get_int(config_manager_t *manager, const char *param_name, int64_t default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_INT) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    int64_t value = param->value.int_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 查找配置参数
config_param_t* config_find_param(config_manager_t *manager, const char *param_name) {
    if (!manager || !param_name) {
        return NULL;
    }
    
    config_group_t *group = manager->groups;
    while (group) {
        config_param_t *param = group->params;
        while (param) {
            if (strcmp(param->name, param_name) == 0) {
                return param;
            }
            param = param->next;
        }
        group = group->next;
    }
    
    return NULL;
}

// 解析大小字符串 (1K, 2M, 3G)
uint64_t config_parse_size(const char *size_str) {
    if (!size_str) {
        return 0;
    }
    
    char *endptr;
    double value = strtod(size_str, &endptr);
    
    if (value < 0) {
        return 0;
    }
    
    uint64_t multiplier = 1;
    if (*endptr) {
        switch (toupper(*endptr)) {
            case 'K':
                multiplier = 1024;
                break;
            case 'M':
                multiplier = 1024 * 1024;
                break;
            case 'G':
                multiplier = 1024 * 1024 * 1024;
                break;
            case 'T':
                multiplier = 1024ULL * 1024 * 1024 * 1024;
                break;
            default:
                multiplier = 1;
                break;
        }
    }
    
    return (uint64_t)(value * multiplier);
}

// 解析时间字符串 (100ms, 1s, 2m, 3h)
uint64_t config_parse_time(const char *time_str) {
    if (!time_str) {
        return 0;
    }
    
    char *endptr;
    double value = strtod(time_str, &endptr);
    
    if (value < 0) {
        return 0;
    }
    
    uint64_t multiplier = 1; // 默认毫秒
    if (*endptr) {
        if (strncmp(endptr, "ms", 2) == 0) {
            multiplier = 1;
        } else if (*endptr == 's') {
            multiplier = 1000;
        } else if (*endptr == 'm') {
            multiplier = 60 * 1000;
        } else if (*endptr == 'h') {
            multiplier = 60 * 60 * 1000;
        }
    }
    
    return (uint64_t)(value * multiplier);
}

// 从文件加载配置
int config_load_from_file(config_manager_t *manager, const char *filename) {
    if (!manager || !filename) {
        return -1;
    }
    
    FILE *file = fopen(filename, "r");
    if (!file) {
        return -1;
    }
    
    char line[1024];
    int line_number = 0;
    
    while (fgets(line, sizeof(line), file)) {
        line_number++;
        
        // 移除换行符
        char *newline = strchr(line, '\n');
        if (newline) {
            *newline = '\0';
        }
        
        // 跳过空行和注释
        char *trimmed = line;
        while (isspace(*trimmed)) trimmed++;
        if (*trimmed == '\0' || *trimmed == '#') {
            continue;
        }
        
        // 解析参数=值
        char *equals = strchr(trimmed, '=');
        if (!equals) {
            continue; // 跳过无效行
        }
        
        *equals = '\0';
        char *param_name = trimmed;
        char *value_str = equals + 1;
        
        // 移除前后空格
        while (isspace(*param_name)) param_name++;
        char *end = param_name + strlen(param_name) - 1;
        while (end > param_name && isspace(*end)) *end-- = '\0';
        
        while (isspace(*value_str)) value_str++;
        end = value_str + strlen(value_str) - 1;
        while (end > value_str && isspace(*end)) *end-- = '\0';
        
        // 设置参数值
        config_set_from_string(manager, param_name, value_str);
    }
    
    fclose(file);
    return 0;
}

// 保存配置到文件
int config_save_to_file(config_manager_t *manager, const char *filename) {
    if (!manager || !filename) {
        return -1;
    }
    
    FILE *file = fopen(filename, "w");
    if (!file) {
        return -1;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    fprintf(file, "# GuDB Configuration File\n");
    fprintf(file, "# Generated at: %s\n", ctime(&(time_t){time(NULL)}));
    fprintf(file, "\n");
    
    config_group_t *group = manager->groups;
    while (group) {
        fprintf(file, "# [%s] %s\n", group->name, group->description);
        
        config_param_t *param = group->params;
        while (param) {
            if (param->is_set) {
                fprintf(file, "# %s\n", param->description);
                
                switch (param->type) {
                    case CONFIG_TYPE_INT:
                        fprintf(file, "%s = %ld\n", param->name, param->value.int_val);
                        break;
                    case CONFIG_TYPE_UINT:
                        fprintf(file, "%s = %lu\n", param->name, param->value.uint_val);
                        break;
                    case CONFIG_TYPE_BOOL:
                        fprintf(file, "%s = %s\n", param->name, 
                               param->value.bool_val ? "true" : "false");
                        break;
                    case CONFIG_TYPE_STRING:
                        fprintf(file, "%s = %s\n", param->name, 
                               param->value.string_val ? param->value.string_val : "");
                        break;
                    case CONFIG_TYPE_DOUBLE:
                        fprintf(file, "%s = %.6f\n", param->name, param->value.double_val);
                        break;
                    case CONFIG_TYPE_SIZE:
                        fprintf(file, "%s = %lu\n", param->name, param->value.size_val);
                        break;
                    case CONFIG_TYPE_TIME:
                        fprintf(file, "%s = %lu\n", param->name, param->value.time_val);
                        break;
                }
                fprintf(file, "\n");
            }
            param = param->next;
        }
        
        fprintf(file, "\n");
        group = group->next;
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    
    fclose(file);
    manager->last_saved = time(NULL);
    
    return 0;
}

// 从字符串设置配置参数
int config_set_from_string(config_manager_t *manager, const char *param_name, 
                          const char *value_str) {
    if (!manager || !param_name || !value_str) {
        return -1;
    }
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param) {
        return -1;
    }
    
    switch (param->type) {
        case CONFIG_TYPE_INT: {
            int64_t value = strtoll(value_str, NULL, 10);
            return config_set_int(manager, param_name, value);
        }
        case CONFIG_TYPE_UINT: {
            uint64_t value = strtoull(value_str, NULL, 10);
            return config_set_uint(manager, param_name, value);
        }
        case CONFIG_TYPE_BOOL: {
            bool value = (strcasecmp(value_str, "true") == 0 || 
                         strcasecmp(value_str, "yes") == 0 || 
                         strcasecmp(value_str, "1") == 0);
            return config_set_bool(manager, param_name, value);
        }
        case CONFIG_TYPE_STRING:
            return config_set_string(manager, param_name, value_str);
        case CONFIG_TYPE_DOUBLE: {
            double value = strtod(value_str, NULL);
            return config_set_double(manager, param_name, value);
        }
        case CONFIG_TYPE_SIZE: {
            uint64_t value = config_parse_size(value_str);
            return config_set_size(manager, param_name, value);
        }
        case CONFIG_TYPE_TIME: {
            uint64_t value = config_parse_time(value_str);
            return config_set_time(manager, param_name, value);
        }
    }
    
    return -1;
}

// 定义字符串配置参数
int config_define_string(config_manager_t *manager, const char *group_name,
                        const char *param_name, const char *description,
                        const char *default_value, bool readonly, bool requires_restart) {
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group || config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_STRING;
    if (default_value) {
        size_t len = strlen(default_value) + 1;
        param->value.string_val = config_alloc(len);
        param->default_value.string_val = config_alloc(len);
        if (param->value.string_val && param->default_value.string_val) {
            strcpy(param->value.string_val, default_value);
            strcpy(param->default_value.string_val, default_value);
        }
    }
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 定义双精度浮点配置参数
int config_define_double(config_manager_t *manager, const char *group_name,
                        const char *param_name, const char *description,
                        double default_value, double min_value, double max_value,
                        bool readonly, bool requires_restart) {
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group || config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_DOUBLE;
    param->value.double_val = default_value;
    param->default_value.double_val = default_value;
    param->min_value.double_val = min_value;
    param->max_value.double_val = max_value;
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 定义大小配置参数
int config_define_size(config_manager_t *manager, const char *group_name,
                      const char *param_name, const char *description,
                      uint64_t default_value, uint64_t min_value, uint64_t max_value,
                      bool readonly, bool requires_restart) {
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group || config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_SIZE;
    param->value.size_val = default_value;
    param->default_value.size_val = default_value;
    param->min_value.size_val = min_value;
    param->max_value.size_val = max_value;
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 定义时间配置参数
int config_define_time(config_manager_t *manager, const char *group_name,
                      const char *param_name, const char *description,
                      uint64_t default_value, uint64_t min_value, uint64_t max_value,
                      bool readonly, bool requires_restart) {
    if (!manager || !group_name || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_group_t *group = config_get_group(manager, group_name);
    if (!group) {
        config_add_group(manager, group_name, NULL);
        group = config_get_group(manager, group_name);
    }
    
    if (!group || config_find_param(manager, param_name)) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_param_t *param = config_alloc(sizeof(config_param_t));
    if (!param) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    memset(param, 0, sizeof(config_param_t));
    strncpy(param->name, param_name, sizeof(param->name) - 1);
    if (description) {
        strncpy(param->description, description, sizeof(param->description) - 1);
    }
    
    param->type = CONFIG_TYPE_TIME;
    param->value.time_val = default_value;
    param->default_value.time_val = default_value;
    param->min_value.time_val = min_value;
    param->max_value.time_val = max_value;
    param->readonly = readonly;
    param->requires_restart = requires_restart;
    param->is_set = false;
    param->last_modified = 0;
    
    param->next = group->params;
    group->params = param;
    group->param_count++;
    manager->total_params++;
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 设置无符号整数配置参数
int config_set_uint(config_manager_t *manager, const char *param_name, uint64_t value) {
    if (!manager || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_UINT || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    if (value < param->min_value.uint_val || value > param->max_value.uint_val) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_value_t old_value = param->value;
    param->value.uint_val = value;
    param->is_set = true;
    param->last_modified = time(NULL);
    
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 设置布尔配置参数
int config_set_bool(config_manager_t *manager, const char *param_name, bool value) {
    if (!manager || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_BOOL || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_value_t old_value = param->value;
    param->value.bool_val = value;
    param->is_set = true;
    param->last_modified = time(NULL);
    
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 设置字符串配置参数
int config_set_string(config_manager_t *manager, const char *param_name, const char *value) {
    if (!manager || !param_name || !value) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_STRING || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_value_t old_value = param->value;
    
    // 释放旧值
    if (param->value.string_val) {
        config_free(param->value.string_val);
    }
    
    // 设置新值
    size_t len = strlen(value) + 1;
    param->value.string_val = config_alloc(len);
    if (!param->value.string_val) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    strcpy(param->value.string_val, value);
    
    param->is_set = true;
    param->last_modified = time(NULL);
    
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 获取无符号整数配置参数
uint64_t config_get_uint(config_manager_t *manager, const char *param_name, uint64_t default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_UINT) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    uint64_t value = param->value.uint_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 获取布尔配置参数
bool config_get_bool(config_manager_t *manager, const char *param_name, bool default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_BOOL) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    bool value = param->value.bool_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 获取字符串配置参数
const char* config_get_string(config_manager_t *manager, const char *param_name, const char *default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_STRING) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    const char *value = param->value.string_val ? param->value.string_val : default_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 初始化默认配置参数
void config_init_default_params(config_manager_t *manager) {
    if (!manager) return;
    
    // 通用配置
    config_define_string(manager, CONFIG_GROUP_GENERAL, "data_directory", 
                        "Database data directory", "./data", false, true);
    config_define_uint(manager, CONFIG_GROUP_GENERAL, "max_connections",
                      "Maximum number of concurrent connections", 1000, 1, 10000, false, true);
    config_define_uint(manager, CONFIG_GROUP_GENERAL, "port",
                      "Database server port", 3306, 1024, 65535, false, true);
    config_define_string(manager, CONFIG_GROUP_GENERAL, "bind_address",
                        "Bind address for server", "0.0.0.0", false, true);
    
    // 内存配置
    config_define_size(manager, CONFIG_GROUP_MEMORY, "buffer_pool_size",
                      "Buffer pool size", 128 * 1024 * 1024, 16 * 1024 * 1024, 
                      16ULL * 1024 * 1024 * 1024, false, true);
    config_define_size(manager, CONFIG_GROUP_MEMORY, "query_cache_size",
                      "Query cache size", 64 * 1024 * 1024, 0, 1024 * 1024 * 1024, false, false);
    config_define_uint(manager, CONFIG_GROUP_MEMORY, "max_memory_pools",
                      "Maximum number of memory pools", 16, 1, 256, false, true);
    
    // 存储配置
    config_define_uint(manager, CONFIG_GROUP_STORAGE, "page_size",
                      "Database page size in bytes", 8192, 4096, 65536, true, true);
    config_define_bool(manager, CONFIG_GROUP_STORAGE, "enable_compression",
                      "Enable data compression", false, false, false);
    config_define_uint(manager, CONFIG_GROUP_STORAGE, "checkpoint_interval",
                      "Checkpoint interval in seconds", 300, 10, 3600, false, false);
    
    // 网络配置
    config_define_uint(manager, CONFIG_GROUP_NETWORK, "connection_timeout",
                      "Connection timeout in seconds", 30, 1, 3600, false, false);
    config_define_uint(manager, CONFIG_GROUP_NETWORK, "query_timeout",
                      "Query timeout in seconds", 300, 1, 86400, false, false);
    config_define_bool(manager, CONFIG_GROUP_NETWORK, "enable_ssl",
                      "Enable SSL connections", false, false, true);
    
    // 日志配置
    config_define_string(manager, CONFIG_GROUP_LOGGING, "log_level",
                        "Log level (DEBUG, INFO, WARN, ERROR)", "INFO", false, false);
    config_define_string(manager, CONFIG_GROUP_LOGGING, "log_file",
                        "Log file path", "gudb.log", false, false);
    config_define_size(manager, CONFIG_GROUP_LOGGING, "max_log_size",
                      "Maximum log file size", 100 * 1024 * 1024, 1024 * 1024, 
                      1024 * 1024 * 1024, false, false);
    config_define_bool(manager, CONFIG_GROUP_LOGGING, "enable_slow_query_log",
                      "Enable slow query logging", true, false, false);
    config_define_time(manager, CONFIG_GROUP_LOGGING, "slow_query_threshold",
                      "Slow query threshold in milliseconds", 1000, 100, 600000, false, false);
    
    // 查询配置
    config_define_uint(manager, CONFIG_GROUP_QUERY, "max_joins",
                      "Maximum number of joins in a query", 61, 2, 256, false, false);
    config_define_bool(manager, CONFIG_GROUP_QUERY, "enable_jit",
                      "Enable JIT compilation", true, false, false);
    config_define_uint(manager, CONFIG_GROUP_QUERY, "jit_threshold",
                      "JIT compilation threshold (execution count)", 100, 1, 10000, false, false);
    
    // 事务配置
    config_define_string(manager, CONFIG_GROUP_TRANSACTION, "default_isolation_level",
                        "Default transaction isolation level", "READ_COMMITTED", false, false);
    config_define_uint(manager, CONFIG_GROUP_TRANSACTION, "lock_timeout",
                      "Lock timeout in milliseconds", 5000, 100, 3600000, false, false);
    config_define_uint(manager, CONFIG_GROUP_TRANSACTION, "max_active_transactions",
                      "Maximum number of active transactions", 1000, 10, 100000, false, true);
    
    // 统计信息配置
    config_define_bool(manager, CONFIG_GROUP_STATISTICS, "auto_analyze",
                      "Enable automatic statistics collection", true, false, false);
    config_define_uint(manager, CONFIG_GROUP_STATISTICS, "analyze_threshold",
                      "Auto-analyze threshold (row changes)", 1000, 100, 1000000, false, false);
    config_define_uint(manager, CONFIG_GROUP_STATISTICS, "histogram_buckets",
                      "Number of histogram buckets", 64, 8, 1024, false, false);
}

// 设置双精度浮点配置参数
int config_set_double(config_manager_t *manager, const char *param_name, double value) {
    if (!manager || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_DOUBLE || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    if (value < param->min_value.double_val || value > param->max_value.double_val) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_value_t old_value = param->value;
    param->value.double_val = value;
    param->is_set = true;
    param->last_modified = time(NULL);
    
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 设置大小配置参数
int config_set_size(config_manager_t *manager, const char *param_name, uint64_t value) {
    if (!manager || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_SIZE || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    if (value < param->min_value.size_val || value > param->max_value.size_val) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_value_t old_value = param->value;
    param->value.size_val = value;
    param->is_set = true;
    param->last_modified = time(NULL);
    
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 设置时间配置参数
int config_set_time(config_manager_t *manager, const char *param_name, uint64_t value) {
    if (!manager || !param_name) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_TIME || param->readonly) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    if (value < param->min_value.time_val || value > param->max_value.time_val) {
        pthread_rwlock_unlock(&manager->config_lock);
        return -1;
    }
    
    config_value_t old_value = param->value;
    param->value.time_val = value;
    param->is_set = true;
    param->last_modified = time(NULL);
    
    if (manager->on_config_changed) {
        manager->on_config_changed(param_name, &old_value, &param->value, 
                                  manager->callback_user_data);
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
    return 0;
}

// 获取双精度浮点配置参数
double config_get_double(config_manager_t *manager, const char *param_name, double default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_DOUBLE) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    double value = param->value.double_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 获取大小配置参数
uint64_t config_get_size(config_manager_t *manager, const char *param_name, uint64_t default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_SIZE) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    uint64_t value = param->value.size_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 获取时间配置参数
uint64_t config_get_time(config_manager_t *manager, const char *param_name, uint64_t default_val) {
    if (!manager || !param_name) {
        return default_val;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    config_param_t *param = config_find_param(manager, param_name);
    if (!param || param->type != CONFIG_TYPE_TIME) {
        pthread_rwlock_unlock(&manager->config_lock);
        return default_val;
    }
    
    uint64_t value = param->value.time_val;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return value;
}

// 设置配置变更回调
int config_set_change_callback(config_manager_t *manager,
                              void (*callback)(const char *param_name, 
                                             const config_value_t *old_value,
                                             const config_value_t *new_value,
                                             void *user_data),
                              void *user_data) {
    if (!manager) {
        return -1;
    }
    
    pthread_rwlock_wrlock(&manager->config_lock);
    manager->on_config_changed = callback;
    manager->callback_user_data = user_data;
    pthread_rwlock_unlock(&manager->config_lock);
    
    return 0;
}

// 打印所有配置参数
void config_print_all(config_manager_t *manager) {
    if (!manager) {
        return;
    }
    
    pthread_rwlock_rdlock(&manager->config_lock);
    
    printf("\n=== GuDB Configuration ===\n");
    printf("Total Groups: %u\n", manager->group_count);
    printf("Total Parameters: %u\n", manager->total_params);
    printf("Configuration File: %s\n", manager->config_file);
    printf("Auto Save: %s\n", manager->auto_save ? "enabled" : "disabled");
    printf("\n");
    
    config_group_t *group = manager->groups;
    while (group) {
        printf("[%s] - %s\n", group->name, group->description);
        printf("Parameters: %u\n", group->param_count);
        
        config_param_t *param = group->params;
        while (param) {
            printf("  %s = ", param->name);
            
            switch (param->type) {
                case CONFIG_TYPE_INT:
                    printf("%ld", param->value.int_val);
                    break;
                case CONFIG_TYPE_UINT:
                    printf("%lu", param->value.uint_val);
                    break;
                case CONFIG_TYPE_BOOL:
                    printf("%s", param->value.bool_val ? "true" : "false");
                    break;
                case CONFIG_TYPE_STRING:
                    printf("\"%s\"", param->value.string_val ? param->value.string_val : "");
                    break;
                case CONFIG_TYPE_DOUBLE:
                    printf("%.6f", param->value.double_val);
                    break;
                case CONFIG_TYPE_SIZE:
                    printf("%lu bytes", param->value.size_val);
                    break;
                case CONFIG_TYPE_TIME:
                    printf("%lu ms", param->value.time_val);
                    break;
            }
            
            if (param->readonly) {
                printf(" [readonly]");
            }
            if (param->requires_restart) {
                printf(" [requires restart]");
            }
            printf("\n");
            printf("    Description: %s\n", param->description);
            
            param = param->next;
        }
        printf("\n");
        group = group->next;
    }
    
    pthread_rwlock_unlock(&manager->config_lock);
}